<template>
  <div class="w100 h100">
    <div class="register" v-if="!success">
      <div class="menu">
        <span class="click" @click="changeLogin">登录</span>
        <div></div>
        <span class="click isActive">注册</span>
      </div>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="0px"
        class="demo-ruleForm"
      >
        <el-form-item prop="name">
          <el-input
            v-model="ruleForm.name"
            @focus="modifyFocusItem('register-account')"
            @blur="modifyFocusItem('')"
            placeholder="请输入用户名"
            clearable
          >
            <img slot="prefix" :src="currentFocus==='register-account'?require('../../assets/img/账号.svg'):require('../../assets/img/账号-常态.svg')" alt=""
          /></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input
            v-model="ruleForm.phone"
            @focus="modifyFocusItem('register-phone')"
            @blur="modifyFocusItem('')"
            placeholder="请输入手机号码"
            clearable
          >
            <img slot="prefix" :src="currentFocus==='register-phone'?require('../../assets/img/手机号-激活.png'):require('../../assets/img/手机号-常态.png')" alt="" />
            <span
              v-show="sendAuthCode"
              slot="suffix"
              class="code"
              @click="getVerityCode"
              >获取验证码</span
            >
            <span
              v-show="!sendAuthCode"
              slot="suffix"
              class="resetGet"
              :class="{ allow: authTime == 0 }"
              @click="getVerityCode"
              >重新获取{{ codeCountNum() }}</span
            >
          </el-input>
        </el-form-item>
        <el-form-item prop="verityCode">
          <el-input
            v-model="ruleForm.verityCode"
            @focus="modifyFocusItem('register-verifyNum')"
            @blur="modifyFocusItem('')"
            placeholder="请输入验证码"
            clearable
          >
            <img slot="prefix" :src="currentFocus==='register-verifyNum'?require('../../assets/img/验证码-激活.png'):require('../../assets/img/验证码-常态.png')" alt="" />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            v-model="ruleForm.password"
            @focus="modifyFocusItem('register-password')"
            @blur="modifyFocusItem('')"
            placeholder="请输入账号8至20位密码"
            clearable
          >
            <img slot="prefix" :src="currentFocus==='register-password'?require('../../assets/img/密码-激活.png'):require('../../assets/img/密码-常态.png')" alt="" />
          </el-input>
        </el-form-item>
        <el-form-item prop="newPassword">
          <el-input
            type="password"
            v-model="ruleForm.newPassword"
            @focus="modifyFocusItem('register-confirmPassword')"
            @blur="modifyFocusItem('')"
            placeholder="请确认密码"
            clearable
          >
            <img slot="prefix" :src="currentFocus==='register-confirmPassword'?require('../../assets/img/密码-激活.png'):require('../../assets/img/密码-常态.png')" alt="" />
          </el-input>
        </el-form-item>
        <el-form-item prop="appid">
          <!-- <el-input v-model="ruleForm.appid" placeholder="请选择租户" clearable>
        </el-input> -->
          <el-select 
          @focus="modifyFocusItem('register-tenant')"
          @blur="modifyFocusItem('')"
          class="appselect w100" style="text-align:left" :popper-append-to-body="false" v-model="ruleForm.appid" placeholder="请选择">
            <img slot="prefix" :src="currentFocus==='register-tenant'?require('../../assets/img/租户-激活.png'):require('../../assets/img/租户-常态.png')" alt="" />
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="orgName">
          <el-input
            v-model="ruleForm.orgName"
            @focus="modifyFocusItem('register-org')"
            @blur="modifyFocusItem('')"
            placeholder="请选择组织"
            clearable
            readonly
            @click.native="selectOrg"
          >
            <img slot="prefix" :src="currentFocus==='register-org'?require('../../assets/img/组织-激活.png'):require('../../assets/img/组织-常态.png')" alt="" />
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            class="w100 login-btn"
            style="
              height: 44px;
              margin-top: 10px;
              font-size: 18px;
              font-weight: 530;
            "
            type="primary"
            @click="register();btnBlur($event)"
            >注册</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div v-else class="registerSuccess">
      <el-result icon="success">
        <template slot="icon">
          <img
            style="height: 100px; width: 100px"
            src="../../assets/img/成功.png"
          />
        </template>
        <template slot="title">
          <span class="title">恭喜您，账户已注册成功！</span>
        </template>
        <template slot="subTitle">
          <span class="subTitle">请保管好您的账号密码</span>
        </template>
        <template slot="extra">
          <el-button
            type="primary"
            style="height: 44px; padding: 14px 39px"
            @click="goLogin"
            >去登录{{ countDown() }}</el-button
          >
        </template>
      </el-result>
    </div>
    <dialogPublic
      title="信息选择"
      :show.sync="showUser"
      @doSubmit="newMemberSelect"
      @doClose="() => (showUser = false)"
      :fullscreen="true"
      appendTobody
    >
      <newMemberSelect
        ref="newMember"
        v-if="showUser"
        :seleteSetting="orgMemberSelect"
      ></newMemberSelect>
    </dialogPublic>
  </div>
</template>

<script>
import { applicationQueryList } from "@/api/systemManagement/applicationManagement.js";
import {
  outStaffInsert,
  sendPhoneMessage,
} from "@/api/systemManagement/userManagement.js";
export default {
  props: {
    currentFocus: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      sendAuthCode: true,
      authTime: 0,
      timer: null,
      timer1: null,
      success: false,
      countNum: 3,
      showUser: false,
      orgMemberSelect: {
        type: "dept-select",
        multiple: false, //单选还是多选
        outOrg: "", //是否是外单位
        chosedData: [],
        level: null,
        permission: false,
      },
      options: [],
      ruleForm: {
        name: "",
        phone: "",
        verityCode: "",
        password: "",
        newPassword: "",
        appid: "",
        orgName: "",
        orgId: "",
      },
      rules: {
        name: [{ required: true, message: "请输入用户名", trigger: "change" }],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "change" },
          {
            message: "请输入正确的手机号码",
            trigger: "blur",
            validator: (rule, value, callback) => {
              var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
              if (!myreg.test(value)) {
                return callback(new Error("请输入正确的11位手机号码"));
              } else {
                callback();
              }
            },
          },
        ],
        verityCode: [
          { required: true, message: "请输入验证码", trigger: "change" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
          {
            message: "密码必须是包含字母、数字、特殊符号的8位以上组合",
            trigger: "blur",
            validator: (rule, value, callback) => {
              const mailReg =
                /^(?![A-Za-z0-9]+$)(?![A-Za-z\W]+$)[a-zA-Z0-9_\W]{8,}$/;
              if (!mailReg.test(value) && value) {
                return callback(
                  new Error("密码必须是包含字母、数字、特殊符号的8位以上组合")
                );
              } else {
                callback();
              }
            },
          },
        ],
        newPassword: [
          { required: true, message: "请确认验证码", trigger: "change" },
          {
            message: "密码前后不一致",
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (this.ruleForm.password != value) {
                return callback(new Error("密码前后不一致"));
              } else {
                callback();
              }
            },
          },
        ],
        appid: [{ required: true, message: "请选择租户", trigger: "change" }],
        orgName: [{ required: true, message: "请选择组织", trigger: "change" }],
        orgId: [{ required: true, message: "请选择组织", trigger: "change" }],
      },
    };
  },
  created() {
    this.getSelectData();
  },
  methods: {
    // 当前选中的input框
    modifyFocusItem(type) {
      this.$emit('modifyFocusItem', type)
    },
    btnBlur(e) {
      // el-button按钮点击后默认处于focus选中状态，手动取消掉按钮选中状态
      let target = e.target
      if(target.nodeName === 'SPAN') {
        target = e.target.parentNode
      }
      target.blur()
    },
    //打开选组织组件
    selectOrg() {
      if (this.ruleForm.orgName == "") {
        this.orgMemberSelect.chosedData = [];
      } else {
        this.orgMemberSelect.chosedData = [
          {
            name: this.ruleForm.orgName,
            id: this.ruleForm.orgId,
          },
        ];
      }
      this.showUser = true;
    },
    countDown() {
      if (this.countNum == 0) {
        return "";
      } else {
        return `(${this.countNum}S)`;
      }
    },
    //获取验证码倒计时
    codeCountNum() {
      if (this.authTime == 0) {
        return "";
      } else {
        return `(${this.authTime}s)`;
      }
    },
    //确定选择
    newMemberSelect() {
      let data = this.$refs.newMember.getSelectData();
      this.ruleForm.orgName = data[0].name;
      this.ruleForm.orgId = data[0].id;
      this.showUser = false;
    },
    changeLogin() {
      this.$emit("clickLogin");
    },
    goLogin() {
      this.$emit("clickLogin");
    },
    //注册
    async register() {
      this.$refs["ruleForm"].validate(async (valid) => {
        if (valid) {
          try {
            let formData = JSON.parse(JSON.stringify(this.ruleForm));
            formData.account = formData.phone;
            delete formData.newPassword;
            formData.password = await this.$utils.encryptPassword(
              formData.password
            );
            let res = await outStaffInsert(formData);
            if (res.code == 200) {
              this.success = true;
              this.backBtn();
            }
            setTimeout(() => {});
          } catch (error) {}
        } else {
          this.$message.error("未填写完整");
        }
      });
    },
    //获取短信验证码
    getVerityCode() {
      if (this.ruleForm.phone != "") {
        sendPhoneMessage({ phone: this.ruleForm.phone })
          .then((res) => {
            this.send();
          })
          .catch((error) => {
            this.$message.error(error);
          });
      } else {
        this.$message.warning("请先输入手机号码");
      }
    },
    send() {
      if (!this.timer) {
        this.authTime = 60;
        this.sendAuthCode = false;
        this.timer = setInterval(() => {
          if (this.authTime > 0 && this.authTime <= 60) {
            this.authTime--;
          } else {
            this.sendAuthCode = true;
            clearInterval(this.timer); // 清除定时器
            this.timer = null;
          }
        }, 1000);
      }
    },
    //返回按钮定时
    backBtn() {
      if (!this.timer1) {
        this.countNum = 3;
        this.timer1 = setInterval(() => {
          if (this.countNum > 0 && this.countNum <= 5) {
            this.countNum--;
          } else {
            clearInterval(this.timer1); // 清除定时器
            this.timer1 = null;
          }
        }, 1000);
      }
    },
    //获取应用下拉框数据
    getSelectData() {
      applicationQueryList().then(
        (res) => {
          let arr = res.data.map((item) => {
            const obj = {
              label: item.name,
              value: item.id,
            };
            return obj;
          });
          this.options = arr;
        },
        (error) => {
          this.$message.error(error);
        }
      );
    },
  },
};
</script>

<style lang="less" scoped>
.register {
  margin: 66px 110px 71px 110px;
  height: 455px;
  text-align: center;
  font-family: Source Han Sans CN;
  .menu {
    display: flex;
    width: 146px;
    height: 50px;
    margin: 40px 87px 20px 87px;
    justify-content: space-between;
    font-size: 28px;
    font-weight: 400;
    color: #999999;
    line-height: 27px;
    .isActive {
      color: #0d60b4;
    }
    div {
      width: 1px;
      height: 32px;
      background: #cccccc;
    }
  }
  .code {
    cursor: pointer;
    font-size: 16px;
    font-weight: 400;
    color: #0d60b4;
  }
  .click {
    cursor: pointer;
  }
  .resetGet {
    font-size: 16px;
    font-weight: 400;
    color: #cccccc;
  }
  .allow {
    cursor: pointer;
    color: #0d60b4;
  }
}
.registerSuccess {
  width: 348px;
  height: 294px;
  margin: 180px 98px 0 98px;
  font-family: Source Han Sans CN;
  text-align: center;
  .title {
    font-size: 24px;
    font-weight: 400;
    letter-spacing: 0px;
    color: #22bb5f;
  }
  .subTitle {
    font-size: 16px;
    font-weight: 400;
    color: #999999;
  }
}
.demo-ruleForm /deep/ .el-input__inner {
  padding-left: 40px;
  font-size: 16px;
}
.demo-ruleForm /deep/ .el-input__suffix {
  .el-icon-circle-close:before {
    font-family: "iconfont";
    font-size: 16px;
    content: "\e6b6";
    color: rgba(152, 167, 185, 0.5);
  }
}
.appselect /deep/ .el-select-dropdown__list{
  padding: 8px 0;
}
.login-btn:focus {
  background-color: #0754A3;
}
.login-btn:active {
  background-color: #00468E;
}
</style>